/**
 * This file is part of the DbUnit module for NetBeans IDE
 * Copyright (C) 2009 Pavol Pitoňák
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

package cz.muni.fi.dbunit;

import cz.muni.fi.dbunit.tasks.AddExtendsTask;
import cz.muni.fi.dbunit.tasks.AddImportTask;
import cz.muni.fi.dbunit.tasks.CloseConnectionTask;
import cz.muni.fi.dbunit.tasks.GetConnectionTask;
import cz.muni.fi.dbunit.tasks.GetDataSetTask;
import cz.muni.fi.dbunit.tasks.GetDatabaseOperationTask;
import cz.muni.fi.dbunit.tasks.GetDatabaseTesterTask;
import cz.muni.fi.dbunit.tasks.NewDatabaseTesterTask;
import java.awt.Component;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.project.classpath.ProjectClassPathModifier;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.libraries.Library;
import org.netbeans.api.project.libraries.LibraryManager;
import org.netbeans.modules.junit.JUnitPluginTrampoline;
import org.netbeans.modules.junit.TestUtil;
import org.netbeans.modules.junit.plugin.JUnitPlugin;
import org.netbeans.modules.junit.plugin.JUnitPlugin.CreateTestParam;
import org.netbeans.spi.project.ui.templates.support.Templates;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.loaders.DataObjectNotFoundException;

/**
 *
 * @author Pavol Pitoňák <pavol@pitonak.com>
 */
public final class SimpleTestWizardIterator implements WizardDescriptor.InstantiatingIterator {

    private int index;
    private WizardDescriptor wizard;
    private WizardDescriptor.Panel[] panels;

    /**
     * Initialize panels representing individual wizard's steps and sets
     * various properties for them influencing wizard appearance.
     */
    private WizardDescriptor.Panel[] getPanels() {
        if (panels == null) {
            Project project = Templates.getProject(wizard);
            panels = new WizardDescriptor.Panel[]{
                        new SimpleTestWizardPanel(project, ""),
                        new DbUnitWizardPanel(project)
                    };
            String[] steps = createSteps();
            for (int i = 0; i < panels.length; i++) {
                Component c = panels[i].getComponent();
                if (steps[i] == null) {
                    // Default step name to component name of panel. Mainly
                    // useful for getting the name of the target chooser to
                    // appear in the list of steps.
                    steps[i] = c.getName();
                }
                if (c instanceof JComponent) { // assume Swing components
                    JComponent jc = (JComponent) c;
                    // Sets step number of a component
                    // TODO if using org.openide.dialogs >= 7.8, can use WizardDescriptor.PROP_*:
                    jc.putClientProperty("WizardPanel_contentSelectedIndex", new Integer(i));
                    // Sets steps names for a panel
                    jc.putClientProperty("WizardPanel_contentData", steps);
                    // Turn on subtitle creation on each step
                    jc.putClientProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
                    // Show steps on the left side with the image on the background
                    jc.putClientProperty("WizardPanel_contentDisplayed", Boolean.TRUE);
                    // Turn on numbering of all steps
                    jc.putClientProperty("WizardPanel_contentNumbered", Boolean.TRUE);
                }
            }
        }
        return panels;
    }

    @Override
    public Set instantiate() throws IOException {
        FileObject sourceDir = getDirectoryWithPackage("src");
        FileObject testDir = Templates.getProject(wizard).getProjectDirectory().getFileObject("test");
        if (testDir == null) {
            // Maven project
            testDir = Templates.getProject(wizard).getProjectDirectory().getFileObject("src/test/java");
        }
        
        // get the class
        String targetName = (String) wizard.getProperty(SimpleTestVisualPanel.CLASS_TO_TEST);
        if (targetName == null) {
            targetName = Templates.getTargetName(wizard); // something like DbUnitTest
        } else {
            targetName = targetName.substring(targetName.lastIndexOf(".") + 1); // remove package
        }

        FileObject classToTest = sourceDir.getFileObject(targetName + ".java");

        // create test class(es) for the selected source class
        JUnitPlugin plugin = TestUtil.getPluginForProject(
                Templates.getProject(wizard));

        if (!JUnitPluginTrampoline.DEFAULT.createTestActionCalled(
                plugin,
                new FileObject[]{classToTest})) {
            return null;
        }

        Map<CreateTestParam, Object> params = TestUtil.getSettingsMap(false);

        final FileObject[] testFileObjects = JUnitPluginTrampoline.DEFAULT.createTests(
                plugin,
                new FileObject[]{classToTest},
                testDir,
                params);

        //XXX: What if the selected class is not testable?
        //     It should not be skipped!

        if (testFileObjects == null) {
            throw new IOException();
        }

        final Set<DataObject> dataObjects = new HashSet<DataObject>((int) (testFileObjects.length * 1.5f));
        for (FileObject testFile : testFileObjects) {
            try {
                dataObjects.add(DataObject.find(testFile));
            } catch (DataObjectNotFoundException ex) {
                //XXX - does nothing special - just continues
            }
        }

        if (dataObjects.isEmpty()) {
            throw new IOException("No file was created.");
        }

        FileObject createdFile = dataObjects.iterator().next().getPrimaryFile();

        // add DbUnit's jar to classpath
        Project project = FileOwnerQuery.getOwner(createdFile);
        Library[] libs = new Library[]{LibraryManager.getDefault().getLibrary("DbUnit")};

        if (libs != null) {
            ProjectClassPathModifier.addLibraries(libs, createdFile, ClassPath.COMPILE);
        }

        addMethods(createdFile);

        return dataObjects;
    }

    @Override
    public void initialize(WizardDescriptor wizard) {
        this.wizard = wizard;
    }

    @Override
    public void uninitialize(WizardDescriptor wizard) {
        panels = null;
    }

    @Override
    public WizardDescriptor.Panel current() {
        return getPanels()[index];
    }

    @Override
    public String name() {
        return index + 1 + ". from " + getPanels().length;
    }

    @Override
    public boolean hasNext() {
        return index < getPanels().length - 1;
    }

    @Override
    public boolean hasPrevious() {
        return index > 0;
    }

    @Override
    public void nextPanel() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        index++;
    }

    @Override
    public void previousPanel() {
        if (!hasPrevious()) {
            throw new NoSuchElementException();
        }
        index--;
    }

    @Override
    public void addChangeListener(ChangeListener l) {
    }

    @Override
    public void removeChangeListener(ChangeListener l) {
    }

    // You could safely ignore this method. Is is here to keep steps which were
    // there before this wizard was instantiated. It should be better handled
    // by NetBeans Wizard API itself rather than needed to be implemented by a
    // client code.
    private String[] createSteps() {
        String[] beforeSteps = null;
        Object prop = wizard.getProperty("WizardPanel_contentData");
        if (prop != null && prop instanceof String[]) {
            beforeSteps = (String[]) prop;
        }

        if (beforeSteps == null) {
            beforeSteps = new String[0];
        }

        String[] res = new String[(beforeSteps.length - 1) + panels.length];
        for (int i = 0; i < res.length; i++) {
            if (i < (beforeSteps.length - 1)) {
                res[i] = beforeSteps[i];
            } else {
                res[i] = panels[i - beforeSteps.length + 1].getComponent().getName();
            }
        }
        return res;
    }

    /**
     * 
     * @param type 'src' or 'test'
     * @return
     */
    private FileObject getDirectoryWithPackage(String type) throws IOException {
        String pckg = (String) wizard.getProperty(SimpleTestVisualPanel.PACKAGE);
        pckg = pckg.replace(".", "/");   // convert a.b.c.d -> a/b/c/d

        FileObject projectDirectory = Templates.getProject(wizard).getProjectDirectory();
        FileObject dir = null;
        if ("src".equals(type)) {
            // Maven project
            dir = projectDirectory.getFileObject("src/main/java");
            // Java Web project
            if (dir == null) {
                dir = projectDirectory.getFileObject("src/java");
            }
            // other projects, e.g. Java SE
            if (dir == null) {
                dir = projectDirectory.getFileObject("src");
            }
        }

        if ("test".equals(type)) {
            // Maven project
            dir = projectDirectory.getFileObject("src/test/java");
            // other projects
            if (dir == null) {
                projectDirectory.getFileObject("test");
            }
        }

        if (dir.getFileObject(pckg) != null) {
            dir = dir.getFileObject(pckg);
        } else {
            String tmp = pckg;
            while (pckg.length() > 0) {
                if (pckg.contains("/")) {
                    tmp = pckg.substring(0, pckg.indexOf("/"));
                    dir.createFolder(tmp);
                    pckg = pckg.substring(pckg.indexOf("/") + 1);
                } else {
                    tmp = pckg;
                    dir.createFolder(pckg);
                    pckg = "";
                }
                dir = dir.getFileObject(tmp);
            }
        }
        return dir;
    }

    private void addMethods(FileObject classToModify) throws IOException {
        JavaSource classToModifySource = JavaSource.forFileObject(classToModify);

        // a DbUnit test has to extend DatabaseTestCase
        classToModifySource.runModificationTask(
                new AddExtendsTask()).commit();
        classToModifySource.runModificationTask(
                new AddImportTask("org.dbunit.DatabaseTestCase")).commit();

        // a DbUnit test has to override getDataSet() method
        classToModifySource.runModificationTask(
                new GetDataSetTask(wizard)).commit();
        classToModifySource.runModificationTask(
                new AddImportTask("org.dbunit.dataset.xml.FlatXmlDataSet")).commit();
        classToModifySource.runModificationTask(
                new AddImportTask("java.io.FileInputStream")).commit();

        // a DbUnit test has to override getConnection() method
        classToModifySource.runModificationTask(
                new GetConnectionTask(wizard, getConnectionType(false))).commit();
        classToModifySource.runModificationTask(
                new AddImportTask(getConnectionType(true))).commit();
        classToModifySource.runModificationTask(
                new AddImportTask("java.sql.Connection")).commit();
        classToModifySource.runModificationTask(
                new AddImportTask("java.sql.DriverManager")).commit();

        if (wizard.getProperty(DbUnitVisualPanel.SET_UP_OPERATION) != null) {
            classToModifySource.runModificationTask(
                    new GetDatabaseOperationTask(wizard, 0)).commit();
        }

        if (wizard.getProperty(DbUnitVisualPanel.TEAR_DOWN_OPERATION) != null) {
            classToModifySource.runModificationTask(
                    new GetDatabaseOperationTask(wizard, 1)).commit();
        }

        Boolean generate = (Boolean) wizard.getProperty(DbUnitVisualPanel.CLOSE_CONNECTION);
        if (generate != null && generate.booleanValue()) {
            classToModifySource.runModificationTask(
                    new CloseConnectionTask(wizard)).commit();
        }

        generate = (Boolean) wizard.getProperty(DbUnitVisualPanel.GET_DATABASE_TESTER);
        if (generate != null && generate.booleanValue()) {
            classToModifySource.runModificationTask(
                    new GetDatabaseTesterTask(wizard)).commit();
        }

        generate = (Boolean) wizard.getProperty(DbUnitVisualPanel.NEW_DATABASE_TESTER);
        if (generate != null && generate.booleanValue()) {
            classToModifySource.runModificationTask(
                    new NewDatabaseTesterTask(wizard)).commit();
        }
    }

    /**
     * Get connection type from database connection url.
     * E.g. for URL 'jdbc:mysql://localhost:3306/test' it will return MySqlConnection
     * or org.dbunit.ext.mysql.MySqlConnection.
     * @param fqn if it should return fully qualified class name
     * @return connection type
     */
    private String getConnectionType(boolean fqn) {
        String type = (String) wizard.getProperty(DbUnitVisualPanel.DATABASE_URL);
        if (type == null || type.length() == 0) {
            return fqn ? "org.dbunit.database.DatabaseConnection" : "DatabaseConnection";
        }
        type = type.split(":")[1];

        if (type.equals("mysql")) {
            return fqn ? "org.dbunit.ext.mysql.MySqlConnection" : "MySqlConnection";
        }

        if (type.equals("db2")) {
            return fqn ? "org.dbunit.ext.db2.Db2Connection" : "org.dbunit.ext.db2.Db2Connection";
        }

        if (type.equals("h2")) {
            return fqn ? "org.dbunit.ext.h2.H2Connection" : "H2Connection";
        }

        if (type.equals("hsqldb")) {
            return fqn ? "org.dbunit.ext.hsqldb.HsqldbConnection" : "HsqldbConnection";
        }

        if (type.equals("mssql")) {
            return fqn ? "org.dbunit.ext.mssql.MsSqlConnection" : "MsSqlConnection";
        }

        if (type.equals("oracle")) {
            return fqn ? "org.dbunit.ext.oracle.OracleConnection" : "OracleConnection";
        }

        return fqn ? "org.dbunit.database.DatabaseConnection" : "DatabaseConnection";
    }

}
            
        
